<?php

class UserController extends Zend_Controller_Action{

    public function init()
    {
        /* Initialize action controller here */
    }
	public function indexAction(){
		$auth=Zend_Auth::getInstance();
		if($auth->hasIdentity()){
			$this->view->identity=$auth->getIdentity();
		}else{
			$this->view->identity=null;
			$this->_forward('login');
		}
	}
	public function loginAction(){
		$userLoginFrm=new Form_UserLoginForm();
		$userLoginFrm->setAction($this->getRequest()->getBaseUrl().'/user/login');
		$userLoginFrm->setMethod('post');
		$request=$this->getRequest();
		if($this->getRequest()->isPost() && $userLoginFrm->isValid($_POST)){
			//setup adapter
			$db=Zend_Db_Table::getDefaultAdapter();
			//create auth adapter
			$authAdapter=new Zend_Auth_Adapter_DbTable($db,'users','username','password');
			//setusername and password
			$authAdapter->setIdentity($_POST['username']);
			$authAdapter->setCredential(md5($_POST['password']));
			//authenticate
			$result=$authAdapter->authenticate();
			if($result->isValid()){
				//store the username, first and last names of the user
				$auth=Zend_Auth::getInstance();
				$storage=$auth->getStorage();
				$storage->write($authAdapter->getResultRowObject(
					array('username','first_name','last_name','role')
				));
				return $this->_forward('index','admin');
			}else{
				
			}
		}
		$this->view->userLoginForm=$userLoginFrm;
	}
	public function logoutAction(){
		$authAdapter=Zend_Auth::getInstance();
		$authAdapter->clearIdentity();
		$this->_forward('index');
	}
}
?>